package com.exe.rege.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exe.rege.common.CustomException;
import com.exe.rege.entity.CategoryEntity;
import com.exe.rege.entity.DishEntity;
import com.exe.rege.entity.SetmealEntity;
import com.exe.rege.mapper.CategoryMapper;
import com.exe.rege.service.CategoryService;
import com.exe.rege.service.DishService;
import com.exe.rege.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryEntity> implements CategoryService {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;


    /**
     * 根据id删除分类，在删除之前要进行判断，与其他有联结的不能删
     * @param ids
     */
    @Override
    public void remove(Long ids) {
        //查询当前要删除的分类是否和菜品有关联
        LambdaQueryWrapper<DishEntity> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(DishEntity::getCategoryId, ids);
        int dishCount = dishService.count(dishQueryWrapper);
        //当查到的关联菜品大于0时，就抛出异常，全局来捕捉异常
        if (dishCount > 0){
            //当有菜品时，则抛出异常
            throw new CustomException("当下分类关联了菜品，不能直接删除。");
        }

        //查询套餐和分类的关联
        LambdaQueryWrapper<SetmealEntity> setmealQueryWrapper = new LambdaQueryWrapper<>();
        setmealQueryWrapper.eq(SetmealEntity::getCategoryId, ids);
        int setmealCount = setmealService.count(setmealQueryWrapper);
        if (setmealCount > 0){
            throw new CustomException("当下分类关联了套餐，不能直接删除。");
        }

        //确定没有关联后即可删除
        //使用父类ServiceImpl的方法
        super.removeById(ids);
    }
}
